package com.example.demo.mapper;

import com.example.demo.model.Product;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ProductMapper {
    @Select("SELECT * FROM product WHERE stock > 0 OR stock = -1")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "description", column = "description"),
            @Result(property = "price", column = "price"),
            @Result(property = "type", column = "type"),
            @Result(property = "duration", column = "duration"),
            @Result(property = "stock", column = "stock"),
            @Result(property = "createdAt", column = "created_at")
    })
    List<Product> findAvailableProducts();

    @Update("UPDATE product SET stock = stock - 1 WHERE id = #{id} AND stock > 0")
    int decreaseStock(@Param("id") Long id);


    @Select("SELECT * FROM product WHERE id = #{id}")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "description", column = "description"),
            @Result(property = "price", column = "price"),
            @Result(property = "type", column = "type"),
            @Result(property = "duration", column = "duration"),
            @Result(property = "stock", column = "stock"),
            @Result(property = "createdAt", column = "created_at")
    })
    Product findById(@Param("id") Long id);

    @Select("SELECT * FROM product")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "description", column = "description"),
            @Result(property = "price", column = "price"),
            @Result(property = "type", column = "type"),
            @Result(property = "duration", column = "duration"),
            @Result(property = "stock", column = "stock"),
            @Result(property = "createdAt", column = "created_at")
    })
    List<Product> findAllProducts();

    @Insert("INSERT INTO product (name, description, price, type, duration, stock, created_at) " +
            "VALUES (#{name}, #{description}, #{price}, #{type}, #{duration}, #{stock}, NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertProduct(Product product);

    @Update("UPDATE product SET name = #{name}, description = #{description}, price = #{price}, " +
            "type = #{type}, duration = #{duration}, stock = #{stock} WHERE id = #{id}")
    void updateProduct(Product product);

    @Delete("DELETE FROM product WHERE id = #{id}")
    void deleteProduct(@Param("id") Long id);
}